import axios from 'axios'
import qs from 'qs'

//API global control
axios.defaults.baseURL = ApiUrl;
axios.defaults.timeout = 60000;
axios.defaults.withCredentials = true; //firefox
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = [function(data) {
  //console.log(qs.stringify(data)); 
  //return a string or an instance of Buffer, ArrayBuffer,FormData or Stream
  return qs.stringify(data);
}];

// Add a request interceptor
axios.interceptors.request.use(function(config) {
  return config;
}, function(error) {
  return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function(response) {
  //console.log('response', response);
  return response;
}, function(error) {
  return Promise.reject(error);
});

//axios 
function requestEntrance(data, callback) {
  if (typeof(callback) === 'object') {
    callback.success = callback.success || function() {};
    callback.error = callback.error || function() {};
    callback.complete = callback.complete || function() {};
    axios(data)
      .then(function(response) {
        if (response) {
          callback.complete();
          callback.success(response.data);
        }
      })
      .catch(function(error) {
        callback.complete();
        callback.error(error);
        alert('Oops! There was a problem connecting to the network. Please refresh!(' + data.url + ')');
        console.log('error:', data.url, error);
      });
  }
}

/****************************** api **************************/
//API get_profile_options
export function test(obj) {
  let requestData = {
      method: 'post',
      url: 'test.php',
      data: obj.data
    },
    requestCallback = {};

  requestCallback.success = function(response) {
    obj.success ? obj.success(response) : '';
  };

  requestEntrance(requestData, requestCallback);
}
